#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QColor>
#include <QStandardItem>
#include <QModelIndex>
#include <QMessageBox>
#include <QDebug>
#include "calfunc.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
//    设置cpuWidget
    QColor color[5];
    color[0]=Qt::red;
    color[1]=Qt::blue;
    color[2]=Qt::darkBlue;
    color[3]=Qt::magenta;
    color[4]=Qt::darkGreen;
    ui->cpuWidget->setLineNum(5,color);
//    设置当前主机
    current_host = 0;
//        启动UDP服务器
    initUdpServer(5555);
    initTreeView();
}

Widget::~Widget()
{
    delete udpSocket;
    delete ui;
    QMap <quint32,t_host_perform*>::ConstIterator ite = host_map.constBegin();
    while (ite !=  host_map.constEnd()) {
       delete *ite;
        ++ite;
     }
}

void Widget::initUdpServer(int port)
{
    udpSocket=new QUdpSocket(this);
    if(!udpSocket->bind(QHostAddress::Any,port))
    {
        QMessageBox msg(this);
        msg.setText(udpSocket->errorString());
        msg.exec();
    }
//    这里是qt的connect，不是socket中的connect
//    表示将slot和SIGNAL联系起来
    connect(udpSocket,SIGNAL(readyRead()),
            this,SLOT(readPendingDatagrams()));
}
void Widget::readPendingDatagrams()
{
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(),datagram.size(),
                                &sender,&senderPort);
        this->resolv_dgram(sender,&datagram);
    }
}
//右边的treeView主机列表初始化
//详细资料搜索treeView用法
void Widget::initTreeView()
{
    model= new QStandardItemModel(0,1);
    model->setHeaderData(0,Qt::Horizontal,"HostList");
     ui->hostList->setModel(model);
}

//datagram format
//HOSTINFO\n
//CPU,1,2,3,4,5\n
//MEM,1,2,3,4,5\n
//TRAFFIC,0,0,0

bool Widget::resolv_dgram(QHostAddress host, const QByteArray *dgram)
{
    //    此行输出调试信息，可删除
    qDebug()<<*dgram;
    //    以'\n'换行符分割字符串
    QList<QByteArray> rf_array_list = dgram->split('\n');
    //    数据报头检测失败
    if(rf_array_list.at(0)  != "HOSTINFO")
    {
        return -1;
    }
    QList <QStandardItem *> founded_item =  model->findItems(host.toString());
    if(founded_item.size()==0)
    {
        QStandardItem *item1 = new QStandardItem(host.toString());
        model->appendRow(item1);
        item1->appendRow(new QStandardItem("CPU"));
        item1->appendRow(new QStandardItem("Memory"));
        item1->appendRow(new QStandardItem("Traffic"));
        host_map[host.toIPv4Address()] = new t_host_perform;
        founded_item.push_front(item1);
    }
    int i;
    for(i=1;i<rf_array_list.size();i++)
    {
        if(rf_array_list.at(i).contains("CPU"))
        {
            founded_item.first()->child(0)->setText(rf_array_list.at(i));
            resolv_cpu(host,&(rf_array_list.at(i)));
        }
        else if(rf_array_list.at(i).contains("MEM"))
        {
            founded_item.first()->child(1)->setText(rf_array_list.at(i));
            resolv_mem(host,&(rf_array_list.at(i)));
        }
        else if(rf_array_list.at(i).contains("TRAFFIC"))
        {
            founded_item.first()->child(2)->setText(rf_array_list.at(i));
            resolv_mem(host,&(rf_array_list.at(i)));
        }

    }
    quint32 ip_int = host.toIPv4Address();
    if(current_host == 0)
        current_host = ip_int;
    if(ip_int == current_host)
    {
        pushCpuData(host_map[ip_int]->cpu[PERFORM_ARRAY_SIZE-1]);
        pushMemData(host_map[ip_int]->mem[PERFORM_ARRAY_SIZE-1]);
        pushTrafficData((host_map[ip_int]->traffic[PERFORM_ARRAY_SIZE-1]));
    }
    return 0;
}

//解析CPU数据行
//datagram format
//CPU,1,2,3,4,5\n
void Widget::resolv_cpu(QHostAddress host, const QByteArray *dgram)
{
    QList <QByteArray> cpu = dgram->split(',');
    //保证一定能够找到对应主机
    QList <QStandardItem *> founded_item =  model->findItems(host.toString());
    quint32 ip_int = host.toIPv4Address();
    QBrush br;
    if(cpu[1].toFloat() < 20)
        br.setColor(Qt::red);
    else if(cpu[1].toFloat() < 40)
        br.setColor(Qt::magenta);
    else br.setColor(Qt::darkGreen);
    founded_item.first()->setForeground(br);
    int i;
//    数组移动耗时，可否链表或STL处理
    for(i=0;i<PERFORM_ARRAY_SIZE-1;i++)
    {
        host_map[ip_int]->cpu[i]=host_map[ip_int]->cpu[i+1];
    }
    // 新收取的数据添加到对应主机性能数组的最后一个
    host_map[ip_int]->cpu[PERFORM_ARRAY_SIZE-1].idle=cpu[1].toDouble();
    host_map[ip_int]->cpu[PERFORM_ARRAY_SIZE-1].iowait=cpu[2].toDouble();
    host_map[ip_int]->cpu[PERFORM_ARRAY_SIZE-1].nice=cpu[3].toDouble();
    host_map[ip_int]->cpu[PERFORM_ARRAY_SIZE-1].sys=cpu[4].toDouble();
    host_map[ip_int]->cpu[PERFORM_ARRAY_SIZE-1].user=cpu[5].toDouble();
}

void Widget::resolv_mem(QHostAddress host, const QByteArray *dgram)
{
    QList <QByteArray> mem = dgram->split(',');
    QList <QStandardItem *> founded_item =  model->findItems(host.toString());
    quint32 ip_int = host.toIPv4Address();
    for(int i=0;i<PERFORM_ARRAY_SIZE-1;i++)
    {
        host_map[ip_int]->mem[i]=host_map[ip_int]->mem[i+1];
    }
    host_map[ip_int]->mem[PERFORM_ARRAY_SIZE-1].free = mem[1].toFloat();
    host_map[ip_int]->mem[PERFORM_ARRAY_SIZE-1].cache = mem[2].toFloat();
    host_map[ip_int]->mem[PERFORM_ARRAY_SIZE-1].swap = mem[3].toFloat();
    host_map[ip_int]->mem[PERFORM_ARRAY_SIZE-1].share = mem[4].toFloat();
}

void Widget::resolv_traffic(QHostAddress host, const QByteArray *dgram)
{
    QList <QByteArray> traffic = dgram->split(',');
    QList <QStandardItem *> founded_item =  model->findItems(host.toString());
    quint32 ip_int = host.toIPv4Address();

    founded_item.first()->child(2)->setText(*dgram);
    for(int i=0;i<PERFORM_ARRAY_SIZE-1;i++)
    {
        host_map[ip_int]->traffic[i]=host_map[ip_int]->traffic[i+1];
    }
    host_map[ip_int]->traffic[PERFORM_ARRAY_SIZE-1].inbound = traffic[1].toFloat();
    host_map[ip_int]->traffic[PERFORM_ARRAY_SIZE-1].outbound = traffic[2].toFloat();
}

void Widget::on_hostList_doubleClicked(QModelIndex index)
{
//    qDebug()<<index.data();
    QHostAddress selected;
//    Address is selected
    if(selected.setAddress(index.data().toString()) && selected.toIPv4Address() != current_host)
    {
        current_host = selected.toIPv4Address();
        ui->titleLabel->setText(QString("主机%1的性能信息").arg(selected.toString()));
        t_host_perform *perform = host_map[selected.toIPv4Address()];
        for(int i=0;i<PERFORM_ARRAY_SIZE;i++)
        {
            pushCpuData(perform->cpu[i]);
            pushMemData(perform->mem[i]);
            pushTrafficData(perform->traffic[i]);
        }
    }
}

void Widget::pushCpuData(t_cpuinfo &cpuinfo)
{
    double data[5];
    data[0]=cpuinfo.idle;
    data[1]=cpuinfo.iowait;
    data[2]=cpuinfo.nice;
    data[3]=cpuinfo.sys;
    data[4]=cpuinfo.user;
    ui->cpuWidget->pushData(data);
}
void Widget::pushMemData(t_meminfo &meminfo)
{
    double data[4];
    data[0]=meminfo.free;
    data[1]=meminfo.cache;
    data[2]=meminfo.share;
    data[3]=meminfo.swap;
    ui->memWidget->pushData(data);
}
void Widget::pushTrafficData(t_traffic_info &traffic)
{
    double data[2];
    data[0]=traffic.inbound;
    data[1]=traffic.outbound;
    ui->traficWidget->pushData(data);
}
